package com.zh.common.vo;


import com.zh.common.exception.ServiceException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;

import java.util.List;

/**
 * 统一的接口调用结果返回
 *
 * @author Lilong 2019/7/24
 */

@Data
@AllArgsConstructor
@ToString
@Builder
public class Result<T> {
    private boolean success;
    private int code;
    private String msg = "success";

    //中文提示
    private String msgZh = "success";

    private T data;

    public Result() {
        this.code = 500;
    }

    public Result(boolean success, int errorCode, String errorMsg) {
        this.success = success;
        this.code = errorCode;
        this.msg = errorMsg;
    }

    public Result(T data) {
        this();
        this.setCode(200);
        this.setSuccess(true);
        this.data = data;
    }

    public Result(List<T> list) {
        this();
        this.setCode(200);
        this.setSuccess(true);
        this.data = (T) list;
    }

    public Result(Throwable e) {
        this();
        //自定义异常
        if (e instanceof ServiceException) {
            this.setMsg(((ServiceException) e).getMsg());
            this.setCode(((ServiceException) e).getCode());
        } else {
            this.setMsg("未知异常");
        }
    }

    /**
     * 返回成功
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result succeed(T data) {
        return Result.<T>builder()
                .code(200)
                .success(true)
                .data(data)
                .build();
    }

    public static <T> Result succeed() {
        return Result.<T>builder()
                .code(200)
                .success(true)
                .build();
    }

    /**
     * 返回成功
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result failed(T data) {
        return Result.<T>builder()
                .code(200)
                .success(false)
                .data(data)
                .build();
    }

    public static <T> Result failed(String errs, T data) {
        return Result.<T>builder()
                .code(200)
                .success(false)
                .data(data)
                .msg(errs)
                .msgZh(errs)
                .build();
    }

    public static <T> Result failed(String error, String errorZh, T data) {
        return Result.<T>builder()
                .code(200)
                .success(false)
                .data(data)
                .msg(error)
                .msgZh(errorZh)
                .build();
    }

}


